package nio;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author Cheng Jun
 * Description: The FileChannel reads data from and to files.
 * @version 1.0
 * @date 2022/8/15 15:39
 */
public class FileChannelExample {
    public static void main(String[] args) throws IOException {
        // RandomAccessFile的实例同时支持对随机访问文件的读写。随机访问文件的行为就像存储在文件系统中的一个大字节数组。
        RandomAccessFile aFile = new RandomAccessFile("src/nio/file/FotChannel.txt", "rw");
        FileChannel inChannel = aFile.getChannel();

        ByteBuffer buf = ByteBuffer.allocate(48);

        int bytesRead = inChannel.read(buf);
        while (bytesRead != -1) {
            System.out.println("Read " + bytesRead);
            buf.flip();
            while (buf.hasRemaining()) {
                System.out.print((char) buf.get());
            }
            buf.clear();
            bytesRead = inChannel.read(buf);
        }
        aFile.close();
    }
}
